//
//  ShoppingProductListViewController.m
//  PeopleStreet
//
//  Created by 喻飞 on 15/12/28.
//  Copyright © 2015年 yuf. All rights reserved.
//

#import "ShoppingProductListViewController.h"
#import "ShoppingProductListCell.h"
#import "SingleChoseMenu.h"
#import "ShoppingProductDetailViewController.h"
static NSString *CellWithIdentifier = @"ShoppingProductListCell";
@interface ShoppingProductListViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITextFieldDelegate>{
    NSInteger _totle;
}

@property (strong, nonatomic) UISwipeGestureRecognizer * rightGesture;
@property (strong, nonatomic) IBOutlet UIButton *maskView;
@property (strong, nonatomic) IBOutlet UIView *choseTypeView;//筛选View
@property (strong, nonatomic) IBOutlet UITextField *lowPriceField;
@property (strong, nonatomic) IBOutlet UITextField *heightPriceField;
@property (strong, nonatomic) IBOutlet UITextField *searchField;//搜索内容
@property (strong, nonatomic) IBOutlet UILabel *bagNumber;//购物车数量
@property (strong, nonatomic) IBOutlet UIView *navSearchView;
@property(nonatomic,assign)NSInteger selectedIndex;
@property(nonatomic,strong)NSMutableArray * goodsArray;
@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong, nonatomic) IBOutlet UIButton *priceOrderButton;//价格降序按钮
@property (strong, nonatomic)IBOutlet UIButton *screenOrderButton;//销量排序按钮

@property(nonatomic,assign)NSInteger count;//按钮点击计数
@property(nonatomic,strong)NSString * brandId;

@property(nonatomic,strong)SingleChoseMenu * goodsBands;
@property(nonatomic,strong)SingleChoseMenu * goodsCategory;
@property(nonatomic,strong)SingleChoseMenu * goodsType;
@end

@implementation ShoppingProductListViewController

- (void)viewWillAppear:(BOOL)animated{
    if ([Common getLoginStatus]) {
        [self getBagNumber];
    }
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (_goodsNameStr) {
        _searchField.text = _goodsNameStr;
    }
    _pageNO =  1;
    self.view.backgroundColor = kGetColor(240, 240, 240);
    self.bagNumber.layer.masksToBounds = YES;
    self.bagNumber.layer.cornerRadius= 6*VerticalRatio();
    _selectedIndex = 101;
    _count = 0;
    _goodsArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
}

#pragma mark  布局调整--=========================================
- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navgationView];
    [self adaptiveViewLayout:self.listCollectionView];
    [self adaptiveViewLayout:self.typeView];
    [self adaptiveViewLayout:self.choseTypeView];
    [self adaptiveViewLayout:self.navSearchView];
    
    [self.maskView addGestureRecognizer:self.rightGesture];
    self.rightGesture.enabled = NO;
    
    self.navSearchView.layer.masksToBounds = YES;
    self.navSearchView.layer.cornerRadius = 17;
    self.navSearchView.layer.borderWidth = 1;
    self.navSearchView.layer.borderColor = kGetColor(230, 230, 230).CGColor;
    
    
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 3*VerticalRatio();
    self.listCollectionView.collectionViewLayout = flowLayout;
    self.listCollectionView.userInteractionEnabled=YES;
    _listCollectionView.dataSource = self;
    _listCollectionView.delegate = self;
    [self.listCollectionView registerNib:[UINib nibWithNibName:CellWithIdentifier bundle:nil] forCellWithReuseIdentifier:CellWithIdentifier];
    _lowPriceField.leftView = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 10, 30), NO)];
    _lowPriceField.leftViewMode = UITextFieldViewModeAlways;
    _lowPriceField.layer.borderWidth = 1;
    _lowPriceField.layer.borderColor = [UIColor colorWithWhite:0.898 alpha:1.000].CGColor;
    
    _heightPriceField.leftView = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 10, 30), NO)];
    _heightPriceField.leftViewMode = UITextFieldViewModeAlways;
    _heightPriceField.layer.borderWidth = 1;
    _heightPriceField.layer.borderColor = [UIColor colorWithWhite:0.898 alpha:1.000].CGColor;
    
    
    NSArray * Titles = @[@"优惠劵",@"折扣",@"满减"];
    _goodsType = [[SingleChoseMenu alloc]initWithFrame:flexibleFrame(CGRectMake(0, 450, 275, 70), NO) titles:Titles XInterval:10 YInterval:10 defaultColor:[UIColor colorWithRed:0.008 green:0.102 blue:0.141 alpha:1.000] colors:nil cancleSelect:(BOOL)NO complect:^(NSInteger index) {
        NSLog(@"%@",Titles[index]);
    }];
    [_choseTypeView addSubview:_goodsType];
    
    //滚动搜索类型
    ScroTitleView * scroTitle = [[ScroTitleView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 50, 35), NO) Titles:@[@"商品",@"品牌",@"店铺"] complect:^(NSInteger index) {
        
    }];
    scroTitle.userInteractionEnabled = NO;
    [self.navSearchView addSubview:scroTitle];

    
}
#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.listCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.listCollectionView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求产品数据
            [self getGoodsList];
        });
    }];
    // 马上进入刷新状态
    [self.listCollectionView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.goodsArray.count == _totle) {
        [self.listCollectionView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求产品数据
            [self getGoodsList];
        });
    }
    
}
#pragma mark -- 请求数据
- (void)getGoodsList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];

    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    
    if(_CategoryId){
        [dic setObject:_CategoryId forKey:@"mgooCategoryId"];
    }
    if (_searchField.text.length>0) {
        [dic setObject:_searchField.text forKey:@"mgooName"];
    }else{
        [dic setObject:@"" forKey:@"mgooName"];
    }
    
    if (_heightPriceField.text.length>0) {
         [dic setObject:_heightPriceField.text forKey:@"maxPrice"];
    }
    
    if (_lowPriceField.text.length>0) {
         [dic setObject:_lowPriceField.text forKey:@"minPrice"];
    }
    
    if (_brandId.length>0) {
        [dic setObject:_brandId forKey:@"mgooBrandId"];
    }
    
    
    if (_selectedIndex == 101) {
         [dic setObject:@"intelligence" forKey:@"sort"];
    }else  if (_selectedIndex == 102){
         [dic setObject:@"time" forKey:@"sort"];
    }else if (_selectedIndex == 103){
        if (_count%2==0) {
            [dic setObject:@"price_desc" forKey:@"sort"];
        }else{
            [dic setObject:@"price_asc" forKey:@"sort"];
        }
        
    }else if (_selectedIndex == 104){
        [dic setObject:@"saleno" forKey:@"sort"];
//        if (_count%2==0) {
//            [dic setObject:@"DESC" forKey:@"selledCountSort"];
//        }else{
//            [dic setObject:@"ASC" forKey:@"selledCountSort"];
//        }
    }
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_GetGoodsLists withHttpType:@"POST" withTag:SX_GetGoodsList];
    
}

#pragma mark  获取购物袋数量--=========================================
-(void)getBagNumber{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"queryCartProductTotalNum" forKey:@"method"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"userId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryCartProductTotalNum withHttpType:@"POST" withTag:SX_QueryCartProductTotalNum];
}

#pragma   mark  返回======================================
- (IBAction)backClick:(UIButton *)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}
#pragma   mark  跳转购物车======================================
- (IBAction)shoppingBag:(id)sender {
    if (![Common getLoginStatus]) {
        [self ShowLoginPage];
        return;
    }
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ShoppingBag"];
    [self.navigationController   pushViewController:page animated:YES];
}

#pragma mark == 加载品牌
- (void)getCategorys{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"queryMallGoodsRelative" forKey:@"method"];
    if (_goodsNameStr) {
        [dic setObject:_goodsNameStr forKey:@"mgooName"];
    }else{
        [dic setObject:@"" forKey:@"mgooName"];
    }
    [dic setObject:@"" forKey:@"mgooBrandId"];
    if (_CategoryId) {
        [dic setObject:_CategoryId forKey:@"mgooCategoryId"];
    }
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryMallGoodsRelative withHttpType:@"GET" withTag:SX_SX_queryMallGoodsRelative];
    
}
- (IBAction)openChoseBand:(id)sender {
   
    
}
#pragma   mark  类型选择======================================

- (IBAction)choseTheType:(UIButton *)sender {
    
    if (sender.tag == 105) {
        [self getCategorys];
        self.rightGesture.enabled = YES;
         _maskView.hidden = NO;
        _maskView.alpha = 0;
        [UIView animateWithDuration:0.5 animations:^{
            _choseTypeView.frame = flexibleFrame(CGRectMake(45, 0, 375, 568), NO);
            _maskView.alpha = 1;
        } ];
        _lowPriceField.text = @"";
        _heightPriceField.text = @"";
        _brandId = @"";
    }else if (sender.tag == 103){
        _screenOrderButton.selected = NO;
        _priceOrderButton.selected = YES;
    }else if (sender.tag == 104){
        _screenOrderButton.selected = YES;
        _priceOrderButton.selected = NO;
    }
    
    if (sender.tag==_selectedIndex) {
        _count +=1;
        
        if (sender.tag==103) {
            _priceOrderButton.selected = YES;
            _screenOrderButton.selected = NO;
            if (_count%2==0) {//价格升序
                [_priceOrderButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];

            }else{//价格降序
                [_priceOrderButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];

            }
            [self.listCollectionView.header beginRefreshing];
//            [self getGoodsList];
        }else if (sender.tag == 104){
            _screenOrderButton.selected = YES;
            _priceOrderButton.selected = NO;
            if (_count%2==0) {//销量升序
                [_screenOrderButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
            }else{//销量降序
                [_screenOrderButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
            }
            
            [self.listCollectionView.header beginRefreshing];
        }
    return;
        
    }
    _count = 0;
    sender.selected = YES;
    UIButton * button = (UIButton *)[self.view viewWithTag:_selectedIndex];
    button.selected = NO;
    _selectedIndex = sender.tag;
    
    if (sender.tag!=103 && sender.tag!=104) {
        _screenOrderButton.selected = NO;
        _priceOrderButton.selected = NO;
    }
    if (sender.tag!=105) {
        [self.listCollectionView.header beginRefreshing]; 
    }
  
}

- (IBAction)closeChoseTypeView:(id)sender {
    
    [UIView animateWithDuration:0.5 animations:^{
        _choseTypeView.frame = flexibleFrame(CGRectMake(320, 0, 375, 568), NO);
        _maskView.alpha = 0;
    } completion:^(BOOL finished) {
        _maskView.hidden = YES;
        
    }];
    self.rightSwipeGesture.enabled = YES;
}

#pragma mark  === 重置
- (IBAction)reChose:(id)sender {
    _lowPriceField.text = @"";
    _heightPriceField.text = @"";
    _brandId = @"";
    for (int i = 0; i<_goodsBands.subviews.count; i++) {
        UIView * view = _goodsBands.subviews[i];
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton * button = (UIButton *)view;
            button.selected = NO;
            button.layer.borderWidth = 0;
            button.backgroundColor = [UIColor colorWithWhite:0.937 alpha:1.000];
        }
    }
    
    for (int i = 0; i<_goodsCategory.subviews.count; i++) {
        UIView * view = _goodsCategory.subviews[i];
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton * button = (UIButton *)view;
            button.selected = NO;
            button.layer.borderWidth = 0;
            button.backgroundColor = [UIColor colorWithWhite:0.937 alpha:1.000];
        }
    }
    
    for (int i = 0; i<_goodsType.subviews.count; i++) {
        UIView * view = _goodsType.subviews[i];
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton * button = (UIButton *)view;
            button.selected = NO;
            button.layer.borderWidth = 0;
            button.backgroundColor = [UIColor colorWithWhite:0.937 alpha:1.000];
        }
    }
}

#pragma mark == 确定筛选
- (IBAction)sureChoseType:(id)sender {
    [UIView animateWithDuration:0.5 animations:^{
        _choseTypeView.frame = flexibleFrame(CGRectMake(320, 0, 375, 568), NO);
        _maskView.alpha = 0;
    } completion:^(BOOL finished) {
        _maskView.hidden = YES;
        
    }];
    self.rightSwipeGesture.enabled = YES;
    [self addRefreshing];
    
}

#pragma mark ====旋转动画======
-(CABasicAnimation *)rotation:(float)dur degree:(float)degree direction:(int)direction repeatCount:(int)repeatCount
{
    CATransform3D rotationTransform = CATransform3DMakeRotation(degree, 0, 0, direction);
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
    animation.duration  =  dur;
    animation.autoreverses = NO;
    animation.cumulative = NO;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = repeatCount;
    animation.delegate = self;
    
    return animation;
    
}

#pragma mark == 右划手势事件
-(void)action_swipeGesture:(UISwipeGestureRecognizer *)gesture{
    [UIView animateWithDuration:0.5 animations:^{
        _choseTypeView.frame = flexibleFrame(CGRectMake(320, 0, 375, 568), NO);
        _maskView.alpha = 0;
    } completion:^(BOOL finished) {
        _maskView.hidden = YES;
        
    }];
    self.rightSwipeGesture.enabled = YES;
    self.rightGesture.enabled = NO;
    
}
#pragma   mark---- textField
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    _goodsNameStr = textField.text;
    [self.listCollectionView.header beginRefreshing];
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    return YES;
}
#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _goodsArray.count;
    
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(154*VerticalRatio(), 201*VerticalRatio());
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 3*VerticalRatio(), 3*VerticalRatio(), 3*VerticalRatio());
    
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ShoppingProductListCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellWithIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    NSString * image = _goodsArray[indexPath.row][@"appAdertImagUri"];
    if (image.length>0) {
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString: image]];
    }else{
    cell.imageView.image =[UIImage imageNamed:@"cloth1"];
    }
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%@",_goodsArray[indexPath.row][@"mgooPublishPrice"]];
    cell.nameLabel.text = _goodsArray[indexPath.row][@"mgooName"];
   
    return cell;
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    ShoppingProductDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ShoppingProductDetail"];
    page.goodsId = _goodsArray[indexPath.row][@"mgooId"];
    [self.navigationController   pushViewController:page animated:YES];
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [self.listCollectionView.header endRefreshing];
    [self.listCollectionView.footer endRefreshing];
    
    if (tag==SX_GetGoodsList) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
//            _goodsArray = database[@"result"][@"pageRecord"];
            _totle = [database[@"result"][@"totalResults"] integerValue];
            if (_totle > PageSize) {
                __weak __typeof(self) weakSelf = self;
                if (!self.listCollectionView.footer) {
                    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                    self.listCollectionView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                        [weakSelf loadMoreData];
                    }];
                }
            }
            if (self.pageNO == 1) {
                [_goodsArray removeAllObjects];
            }
            NSArray *arr = database[@"result"][@"pageRecord"];
            for (id entity in arr) {
                [_goodsArray addObject:entity];
            }
            [self.listCollectionView reloadData];
           
        }
    }else if (tag == SX_QueryCartProductTotalNum){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _bagNumber.text =[NSString stringWithFormat:@"%@", database[@"result"]];
        }
        
    }else if (tag == SX_SX_queryMallGoodsRelative){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            self.rightSwipeGesture.enabled = NO;
            NSArray * array = database[@"result"][@"mallBrand"];
            NSMutableArray * titles = [NSMutableArray array];
            for (NSString * str in array) {
                NSString * title = [str substringFromIndex:9];
                [titles addObject:title];
            }
            
            _goodsBands = [[SingleChoseMenu alloc]initWithFrame:flexibleFrame(CGRectMake(0, 46, 275, 130), NO) titles:titles XInterval:10 YInterval:10 defaultColor:[UIColor colorWithRed:0.008 green:0.102 blue:0.141 alpha:1.000] colors:nil cancleSelect:(BOOL)NO complect:^(NSInteger index) {
                NSString * str = [NSString stringWithFormat:@"%@",database[@"result"][@"mallBrand"][index]];
                _brandId = [str substringToIndex:8];
            }];
            [_choseTypeView addSubview:_goodsBands];
           
            
            NSArray * Array = database[@"result"][@"mallCategory"];
            NSMutableArray * Titles = [NSMutableArray array];
            for (NSString * str in Array) {
                NSString * title = [str substringFromIndex:9];
                [Titles addObject:title];
            }
            
            
            _goodsCategory = [[SingleChoseMenu alloc]initWithFrame:flexibleFrame(CGRectMake(0, 204, 275, 115), NO) titles:Titles XInterval:10 YInterval:10 defaultColor:[UIColor colorWithRed:0.008 green:0.102 blue:0.141 alpha:1.000] colors:nil cancleSelect:(BOOL)NO complect:^(NSInteger index) {
                NSLog(@"%@",titles[index]);
            }];
            [_choseTypeView addSubview:_goodsCategory];

        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
        
        //
        [self dismissWaitDialog];
        
        
    }
    
- (UISwipeGestureRecognizer *)rightGesture
{
    if (!_rightGesture) {
        _rightGesture = ({
            UISwipeGestureRecognizer * rightSwipeGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(action_swipeGesture:)];
            rightSwipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
            
            rightSwipeGesture;
        });
    }
    return _rightGesture;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
